<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="社区" prop="communityId">
        <el-select
            v-model="queryParams.communityId"
            placeholder="请选择社区"
            clearable
            filterable
            @change="gainCommunityId"
        >
          <el-option v-for="c in community" :label="c.name || c.communityId" :value="c.communityId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼宇" prop="buildingId">
        <el-select
            v-model="queryParams.buildingId"
            placeholder="请选择楼宇"
            clearable
            filterable
        >
          <el-option v-for="b in building" :label="b.name || b.buildingId" :value="b.buildingId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼层数" prop="floorNo">
        <el-input
            v-model="queryParams.floorNo"
            placeholder="请输入楼层数"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="储藏室编号" prop="storageNo">
        <el-input
            v-model="queryParams.storageNo"
            placeholder="请输入储藏室编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建筑面积" prop="buildingArea">
        <el-input
            v-model="queryParams.buildingArea"
            placeholder="请输入建筑面积"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用面积" prop="usableArea">
        <el-input
            v-model="queryParams.usableArea"
            placeholder="请输入使用面积"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公摊面积" prop="publicArea">
        <el-input
            v-model="queryParams.publicArea"
            placeholder="请输入公摊面积"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['comsys:room:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['comsys:room:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['comsys:room:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['comsys:room:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['comsys:room:import']"
        >导入
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="储藏室ID" align="center" prop="storageRoomId"/>
      <el-table-column label="社区" align="center" prop="communityId">
        <template #default="scope">
          <span>{{ getCommunityName(scope.row.communityId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="楼宇" align="center" prop="buildingId">
        <template #default="scope">
          <span>{{ getBuildingName(scope.row.buildingId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="楼层数" align="center" prop="floorNo"/>
      <el-table-column label="储藏室编号" align="center" prop="storageNo"/>
      <el-table-column label="建筑面积" align="center" prop="buildingArea">
        <template #default="scope">
          <span>{{ scope.row.buildingArea ? scope.row.buildingArea + '㎡' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用面积" align="center" prop="usableArea">
        <template #default="scope">
          <span>{{ scope.row.usableArea ? scope.row.usableArea + '㎡' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="房屋类型" align="center" prop="houseType"/>
      <el-table-column label="储物间状态" align="center" prop="roomStatus"/>
      <el-table-column label="公摊面积" align="center" prop="publicArea">
        <template #default="scope">
          <span>{{ scope.row.publicArea ? scope.row.publicArea + '㎡' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description"/>
      <el-table-column label="储藏室图片" align="center" prop="images">
        <template #default="scope">
          <div v-if="scope.row.images" class="table-image-container">
            <el-image
                :src="scope.row.images"
                :preview-src-list="[scope.row.images]"
                class="table-preview-item"
                fit="cover"
                lazy
            />
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['comsys:room:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['comsys:room:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改储藏室管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roomRef" :model="form" :rules="rules" label-width="80px">
        <!-- 社区下拉框 -->
        <el-form-item label="社区">
          <el-select v-model="form.communityId" placeholder="请选择社区" clearable @change="gainCommunityId">
            <el-option v-for="c in community" :label=" c.name || c.communityId" :value="c.communityId"></el-option>
          </el-select>
        </el-form-item>

        <!-- 楼宇下拉框 -->
        <el-form-item label="楼宇">
          <el-select v-model="form.buildingId" placeholder="请选择楼宇">
            <el-option v-for="b in building" :label="b.name || b.buildingId" :value="String(b.buildingId)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼层数" prop="floorNo">
          <el-input v-model="form.floorNo" placeholder="请输入楼层数"/>
        </el-form-item>
        <el-form-item label="储藏室编号" prop="storageNo">
          <el-input v-model="form.storageNo" placeholder="请输入储藏室编号"/>
        </el-form-item>
        <el-form-item label="建筑面积" prop="buildingArea">
          <el-input v-model="form.buildingArea" placeholder="请输入建筑面积"/>
        </el-form-item>
        <el-form-item label="使用面积" prop="usableArea">
          <el-input v-model="form.usableArea" placeholder="请输入使用面积"/>
        </el-form-item>
        <el-form-item label="公摊面积" prop="publicArea">
          <el-input v-model="form.publicArea" placeholder="请输入公摊面积"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="储物间状态" prop="roomStatus">
            <el-select v-model="form.roomStatus" placeholder="请选择或输入储物间状态" clearable filterable allow-create>
              <el-option label="有效" :value="'有效'"></el-option>
              <el-option label="空置" :value="'空置'"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="图片(JSON数组)" prop="images">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/upload/img"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
          >
            <img v-if="form.images" :src="form.images" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Room">
import {listRoom, getRoom, delRoom, addRoom, updateRoom} from "@/api/comsys/room"
import {Plus} from "@element-plus/icons-vue";
import {getToken} from "@/utils/auth.js";
import {ElMessage} from "element-plus";
import request from '@/utils/request'

const {proxy} = getCurrentInstance()

const roomList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const router = useRouter()

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    communityId: null,
    buildingId: null,
    floorNo: null,
    storageNo: null,
    buildingArea: null,
    usableArea: null,
    houseType: null,
    houseStatus: null,
    publicArea: null,
    description: null,
    images: null,
  },
  rules: {}
})

const {queryParams, form, rules} = toRefs(data)

/** 查询储藏室管理列表 */
function getList() {
  loading.value = true
  listRoom(queryParams.value).then(response => {
    roomList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    storageRoomId: null,
    communityId: null,
    buildingId: null,
    floorNo: null,
    storageNo: null,
    buildingArea: null,
    usableArea: null,
    houseType: null,
    houseStatus: null,
    roomStatus: null,
    publicArea: null,
    description: null,
    images: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("roomRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.storageRoomId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 若查询区已选择社区，则带入并加载对应楼宇
  if (queryParams.value.communityId) {
    form.value.communityId = queryParams.value.communityId
    gainCommunityId(queryParams.value.communityId).then(() => {
      form.value.buildingId = null
    })
  } else {
    // 未选择社区则清空楼宇选项与值
    building.value = []
    form.value.buildingId = null
  }
  open.value = true
  title.value = "添加储藏室管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _storageRoomId = row.storageRoomId || ids.value
  getRoom(_storageRoomId).then(response => {
    form.value = response.data
    // 统一楼宇ID类型为字符串，便于 el-select 默认选中
    if (form.value.buildingId !== null && form.value.buildingId !== undefined) {
      form.value.buildingId = String(form.value.buildingId)
    }
    const originalId = form.value.buildingId
    // 根据社区加载楼宇选项，编辑场景保留原值
    gainCommunityId(form.value.communityId, { keepFormBuilding: true, keepQueryBuilding: true }).then(() => {
      form.value.buildingId = originalId
    })
    open.value = true
    title.value = "修改储藏室管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roomRef"].validate(valid => {
    if (valid) {
      if (form.value.storageRoomId != null) {
        updateRoom(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRoom(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _storageRoomIds = row.storageRoomId || ids.value
  proxy.$modal.confirm('是否确认删除储藏室管理编号为"' + _storageRoomIds + '"的数据项？').then(function () {
    return delRoom(_storageRoomIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comsys/room/export', {
    ...queryParams.value
  }, `room_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  router.push({path: '/comsys/room/import'})
}

const headers = ref({Authorization: "Bearer " + getToken()})
// 图片上传
const handleAvatarSuccess = (
    response
) => {
  ElMessage.success("上传成功")
  form.value.images = response.msg
  // console.log(response)
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG or PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

//社区下拉框绑定
const community = ref([]);
const building = ref([])
const initCommunity = () => {
  request({
    url: `/communityVo/getCommunityVoNameById`,
    method: 'get'
  }).then((response) => {
    community.value = response.data;
  })
}

// 映射社区名称
const communityMap = ref({})
const getCommunityName = (cid) => {
  if (cid == null) return '-'
  const key = typeof cid === 'string' ? cid : String(cid)
  return communityMap.value[key] || communityMap.value[cid] || cid
}

watch(community, (list) => {
  const map = {}
  ;(list || []).forEach(c => {
    if (c && c.communityId != null) {
      map[c.communityId] = c.name || c.communityName || c.communityId
    }
  })
  communityMap.value = map
})
const buildingMap = ref({})
const preloadAllBuildings = () => {
  if (!community.value || community.value.length === 0) return
  const tasks = community.value.map(c => request({
    url: `/building/getBuildingVoNameAndId/${c.communityId}`,
    method: 'get'
  }))
  Promise.all(tasks).then(responses => {
    const map = {}
    responses.forEach(resp => {
      const list = resp.data || []
      list.forEach(b => {
        if (b && b.buildingId != null) {
          map[b.buildingId] = b.name || b.buildingId
        }
      })
    })
    buildingMap.value = map
  }).catch(() => {})
}

const getBuildingName = (bid) => {
  if (bid == null) return '-'
  const key = typeof bid === 'string' ? bid : String(bid)
  return buildingMap.value[key] || buildingMap.value[bid] || bid
}

//根据社区联动楼宇（支持保留楼宇值）
const gainCommunityId = (cid, options = { keepFormBuilding: false, keepQueryBuilding: false }) => {
  return new Promise((resolve) => {
    console.log('选中的社区ID:', cid);

    if (!options.keepFormBuilding) {
      form.value.buildingId = null;
    }
    if (!options.keepQueryBuilding && queryParams.value) {
      queryParams.value.buildingId = null;
    }
    building.value = [];

    if (cid) {
      request({
        url: `/building/getBuildingVoNameAndId/${cid}`,
        method: 'get'
      }).then((response) => {
        building.value = response.data;
        resolve();
      })
    } else {
      resolve();
    }
  })
}

watch(community, () => {
  preloadAllBuildings()
})
initCommunity();
getList()
</script>

<style scoped>
.avatar-uploader, .avatar-uploader.el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.avatar-uploader:hover { border-color: var(--el-color-primary); }
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  object-fit: cover;
  display: block;
}
</style>
